﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Msg;

namespace Ledict.ConditionExtract.Frm.NodeTree
{
    /// <summary>
    /// 诉请要素关系配置（XPath）
    /// </summary>
    public partial class FrmSuitTypeRel : BaseForm
    {
        /// <summary>
        /// 情形情节业务逻辑类
        /// </summary>
        readonly CaseCauseBLL _caseCauseBll = new CaseCauseBLL();
        /// <summary>
        /// 生成ID逻辑类
        /// </summary>
        readonly NewIDBLL _newIdbll = new NewIDBLL();

        readonly XmlLabel_SuitTypeRelBLL _xmlLabelSuitTypeRelBll = new XmlLabel_SuitTypeRelBLL();

        /// <summary>
        /// 页面标签与诉情种类关系列表
        /// </summary>
        public IList<SYS_XmlLabel_SuitTypeRel> SysXmlLabelSuitTypeRels { get; set; }
        public string CcId { get; set; }

        /// <summary>
        /// 诉请种类ID
        /// </summary>
        public string StId { get; set; }
        public FrmSuitTypeRel()
        {

            InitializeComponent();
            SysXmlLabelSuitTypeRels = new List<SYS_XmlLabel_SuitTypeRel>();
        }

        /// <summary>
        /// 界面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSuitTypeRel_Load(object sender, EventArgs e)
        {
            var dt = _caseCauseBll.Select_parentNode_Name(CcId);
            if (dt != null && dt.Rows.Count > 0)
            {
                var tn = new TreeNode(dt.Rows[0][1].ToString()) { Tag = dt.Rows[0][0].ToString() };
                treeView1.Nodes.Add(tn);
                if (_caseCauseBll.Select_parentNode_child(tn.Tag.ToString()).Rows.Count > 0)
                {
                    tn.Nodes.Add(new TreeNode());
                }
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            dgvSuitRel.AutoGenerateColumns = false;
            dgvSuitRel.DataSource = SysXmlLabelSuitTypeRels != null && SysXmlLabelSuitTypeRels.Any() ? SysXmlLabelSuitTypeRels.ToList() : null;
        }

        #region 节点效果
        /// <summary>
        /// 节点展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {

            var selectNode = e.Node;
            selectNode.Nodes.Clear();

            var dt = _caseCauseBll.Select_parentNode_child(selectNode.Tag.ToString());
            if (dt.Rows.Count > 0)
            {
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    var childNode = new TreeNode(dt.Rows[i][1].ToString()) { Tag = dt.Rows[i][0] };
                    if (_caseCauseBll.Select_parentNode_child(childNode.Tag.ToString()) != null)
                    {
                        childNode.Nodes.Add(new TreeNode());
                    }
                    selectNode.Nodes.Add(childNode);
                }
            }
        }

        /// <summary>
        /// 节点选择之后，考虑到性能和后期生成XPath的便利，在每次选后都存储数据到内存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Checked)
            {
                if (e.Node.Text.Equals("属性"))
                {
                    MsgBox.Warn("不能选择属性做为节点");
                    return;
                }
                var text = "";
                var tn = e.Node;
                var selectCcid = e.Node.Tag.ToString();
                var labelType = string.Empty;
                //从后往前生成xpath
                do
                {
                    //当前节点值为属性，则排除属性，直接找上级节点
                    if (tn.Text.Equals(@"属性"))
                    {
                        tn = tn.Parent;
                    }

                    if (tn.Text.Equals("诉请要素") || tn.Text.Equals("事实要素") || tn.Text.Equals("基本要素") || tn.Text.Equals("理由要素"))
                    {
                        switch (tn.Text)
                        {
                            case "诉请要素":
                                labelType = "Suit"; break;
                            case "事实要素": labelType = "Fact"; break;
                            case "基本要素":
                            case "理由要素":
                                labelType = "Reason"; break;
                            default: labelType = "Suit"; break;
                        }
                    }


                    if (tn.Parent != null && tn.Parent.Text.Equals(@"属性"))
                    {
                        text = ("/@" + tn.Text) + text;
                    }
                    else
                    {
                        //拼接XPath路径
                        text = ("/" + tn.Text) + text;
                    }
                    if (tn.Parent != null)
                    {
                        tn = tn.Parent;
                    }
                    else
                    {
                        break;
                    }

                } while (true);

                var model = new SYS_XmlLabel_SuitTypeRel()
                {
                    ST_ID = StId,
                    LabelXpath = text,
                    LabelID = selectCcid,
                    LabelType = labelType,
                    IsShowLabel = true,
                    XSR_ID = _newIdbll.JudgeDoc_CreateID("SYS_XmlLabel_SuitTypeRel")
                };

                SysXmlLabelSuitTypeRels.Add(model);

            }
            else
            {
                if (SysXmlLabelSuitTypeRels != null && SysXmlLabelSuitTypeRels.Any(x => x.LabelID == e.Node.Tag.ToString()))
                {
                    var deleteModel = SysXmlLabelSuitTypeRels.FirstOrDefault(x => x.LabelID == e.Node.Tag.ToString());
                    SysXmlLabelSuitTypeRels.Remove(deleteModel);
                }
            }
        }
        #endregion

        #region 生成XPath
        /// <summary>
        /// 生成XPath
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnXPath_Click(object sender, EventArgs e)
        {
            BindData();
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 开始编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvSuitRel_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex != 4)
            {
                return;
            }
        }

        /// <summary>
        /// 结束编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvSuitRel_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4)
            {
                var index = e.RowIndex;
                var showIndex = dgvSuitRel.Rows[index].Cells["ShowIndex"].Value.ToString();

                SysXmlLabelSuitTypeRels[index].ShowIndex = Convert.ToInt32(showIndex);
            }
        }

        /// <summary>
        /// checkbox选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvSuitRel_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //获取checkbox的值（是否显示标签）
            if (e.ColumnIndex == 3 && e.RowIndex != -1)
            {
                //获取控件的值
                var index = e.RowIndex;
                var isShowLabel = dgvSuitRel.Rows[e.RowIndex].Cells["IsShowLabel"].EditedFormattedValue;

                SysXmlLabelSuitTypeRels[index].IsShowLabel = Convert.ToBoolean(isShowLabel);
            }
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (SysXmlLabelSuitTypeRels != null && SysXmlLabelSuitTypeRels.Any())
            {
                if (_xmlLabelSuitTypeRelBll.BatchAdd(SysXmlLabelSuitTypeRels))
                {
                    MsgBox.OK("保存成功");
                    return;
                }
                MsgBox.Err("保存失败");
            }
            else
            {
                MsgBox.Warn("没有任何项需要添加");
            }
        }
        #endregion




    }


}
